<template>
  <div>
    <!-- AI总结 -->
    <el-drawer v-model="drawer" :direction="direction" v-if="typeShow == 1">
      <template #header>
        <div class="header-top">
          <svg-icon
            :icon-class="selectSvgIcons(InfoData)"
            style="font-size: 30px; vertical-align: middle; margin-right: 6px; position: relative"
          ></svg-icon>
          <p class="top">{{ InfoData.realName }}{{ InfoData.suffix ? '.' + InfoData.suffix : '' }}</p>
        </div>
      </template>

      <template #default>
        <div class="content">
          <p class="title">总结内容如下:</p>

          <div class="info" v-loading="loading">
            <div class="text" v-if="txtInfo">
              {{ txtInfo }}
            </div>

            <el-empty v-else description="暂无总结内容" />
          </div>
        </div>
      </template>
    </el-drawer>

    <!-- AI翻译-->
    <el-drawer v-model="ShowTranslate" :direction="direction" v-if="typeShow == 2">
      <template #header>
        <div class="header-top">
          <svg-icon
            :icon-class="selectSvgIcons(InfoData)"
            style="font-size: 30px; vertical-align: middle; margin-right: 6px; position: relative"
          ></svg-icon>
          <p class="top">{{ InfoData.realName }}{{ InfoData.suffix ? '.' + InfoData.suffix : '' }}</p>
        </div>
      </template>

      <template #default>
        <div class="content">
          <p class="title">翻译内容如下:</p>

          <div class="info" v-loading="loading">
            <div class="text" v-if="TranslateInfo">
              {{ TranslateInfo }}
            </div>

            <el-empty v-else description="暂无翻译内容" />
          </div>
        </div>
      </template>
    </el-drawer>

    <!-- AI摘要-->
    <el-drawer v-model="ShowAbstract" :direction="direction" v-if="typeShow == 3">
      <template #header>
        <div class="header-top">
          <svg-icon
            :icon-class="selectSvgIcons(InfoData)"
            style="font-size: 30px; vertical-align: middle; margin-right: 6px; position: relative"
          ></svg-icon>
          <p class="top">{{ InfoData.realName }}{{ InfoData.suffix ? '.' + InfoData.suffix : '' }}</p>
        </div>
      </template>

      <template #default>
        <div class="content">
          <p class="title">摘要内容如下:</p>

          <div class="info" v-loading="loading">
            <div class="text" v-if="AbstractInfo">
              {{ AbstractInfo }}
            </div>

            <el-empty v-else description="暂无摘要内容" />
          </div>
        </div>
      </template>
    </el-drawer>

    <!-- AI抽取-->
    <el-drawer v-model="ShowExtract" :direction="direction" v-if="typeShow == 4">
      <template #header>
        <div class="header-top">
          <svg-icon
            :icon-class="selectSvgIcons(InfoData)"
            style="font-size: 30px; vertical-align: middle; margin-right: 6px; position: relative"
          ></svg-icon>
          <p class="top">{{ InfoData.realName }}{{ InfoData.suffix ? '.' + InfoData.suffix : '' }}</p>
        </div>
      </template>

      <template #default>
        <div class="content">
          <p class="title">抽取内容如下:</p>

          <div class="info" v-loading="loading">
            <div class="text" v-if="ExtractInfo">
              {{ ExtractInfo }}
            </div>

            <el-empty v-else description="暂无抽取内容" />
          </div>
        </div>
      </template>
    </el-drawer>

    <!-- AI问答(取消)-->
    <el-drawer v-model="showAiQA" :direction="direction" v-if="typeShow == 5">
      <template #header>
        <div class="header-top">
          <svg-icon
            :icon-class="selectSvgIcons(InfoData)"
            style="font-size: 30px; vertical-align: middle; margin-right: 6px; position: relative"
          ></svg-icon>
          <p class="top">{{ InfoData.realName }}{{ InfoData.suffix ? '.' + InfoData.suffix : '' }}</p>
        </div>
      </template>

      <template #default>
        <div class="content">
          <p class="title">AI问答:</p>

          <div class="chat-container">
            <div class="chat-messages" ref="chatMessages" v-if="messages.length">
              <div v-for="(message, index) in messages" :key="index">
                <!-- 如果是用户消息 -->
                <div v-if="message.isUser" class="user-message">
                  <div class="messageisUser">
                    <div class="message-content user">
                      <span>{{ message.content }}</span>
                    </div>
                    <!-- <div class="avatarUser">管</div> -->
                    <img class="avatarUser" :src="userStore.avatar" alt="暂无" />
                  </div>
                </div>

                <!-- 如果是AI（或其他）消息 -->
                <div v-else class="ai-message">
                  <div class="message-content-wrapper">
                    <svg-icon icon-class="ai_chat2" class="AIavatar"></svg-icon>

                    <!-- <div class="avatar">AI</div> -->
                    <!-- 或者是其他用户的头像 -->
                    <div class="message-content other">
                      <!-- 如果是 loading 状态 -->
                      <span v-if="message.isLoading" class="loading-text">加载中...</span>
                      <!-- 如果不是 loading，显示实际消息 -->
                      <span v-else>{{ message.content }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="chat-messages" ref="chatMessages" v-if="!messages.length">
              <el-empty description="暂无问答内容" />
            </div>

            <!-- 输入框 -->
            <div class="chat-input-container" :class="{ focused: isFocused }">
              <div class="input-bot">
                <div class="page_input">
                  <div class="input_box">
                    <el-input
                      ref="textInputRefs"
                      v-model="messageInput"
                      :autosize="{ minRows: 3, maxRows: 5 }"
                      type="textarea"
                      resize="none"
                      placeholder="请输入内容"
                      @keyup.ctrl.enter.native="handleKeyPress"
                      @keydown.enter.exact.native="enterSubmit"
                      @focus="handleFocus"
                      @blur="handleBlur"
                    >
                      <!-- <template #prefix>
                        <el-icon><Search /></el-icon>
                      </template> -->
                    </el-input>

                    <!-- <el-icon class="icon_search"><Search /></el-icon> -->

                    <div class="btn_box">
                      <div class="voice_box">
                        <img
                          v-if="isSpeakType == 1"
                          src="../../../assets/images/chatgpt/mic.png"
                          style="width: 20px; height: 20px"
                          alt=""
                          @click="startRecordAudio"
                        />
                        <div v-else-if="isSpeakType == 2">
                          <div class="loaderRectangle" @click="stopRecordAudio">
                            <div></div>
                            <div></div>
                            <div></div>
                            <div></div>
                            <div></div>
                          </div>
                        </div>

                        <div v-else-if="isSpeakType == 3" class="SpeakType3">
                          <i class="el-icon-loading"></i>
                          <span>转码中...</span>
                        </div>
                      </div>
                      <el-divider direction="vertical" />
                      <!-- 发送按钮 -->
                      <div class="sendBtn" @click="sendMessage">
                        <svg-icon icon-class="send1"></svg-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 输入框及发送按钮 -->
            <!-- InputText文本输入组件 :clearable="true"(显示清空按钮)-->
            <!-- <div class="chat-input-container">
              <InputText
                class="chat-input"
                @input="inputChangeMethod"
                :maxlength="maxnum"
                :rows="row"
                :placeholder="placeholder"
                v-model="values"
                :values="values"
                :focusMethod="focusMethod"
                @clearValue="updateRows"
              />
             
              <el-button @click="sendMessage" type="primary" :disabled="!messageInput.trim()" class="send-button">发送</el-button>
            </div> -->
            <!-- <el-input v-model="messageInput" type="text" placeholder="请输入消息" @keyup.enter="sendMessage" class="chat-input" /> -->
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { getToken } from '@/utils/auth';
const { proxy } = getCurrentInstance() as any;
import axios from 'axios';
import Recorder from 'js-audio-recorder';
import { Calendar, Search } from '@element-plus/icons-vue';
import InputText from '@/views/personDoc/AiFile/input-text.vue'; // 文本输入组件
import { ApiAISummary, ApiAITranslate, ApiAIAbstract, ApiAIExtract } from '@/api/personDoc/aiApi';
import type { DrawerProps } from 'element-plus';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();

const drawer = ref(false);
const loading = ref(true);
const direction = ref<DrawerProps['direction']>('rtl');
const InfoData = ref({} as any);
const txtInfo = ref('') as any;
const TranslateInfo = ref('') as any;
const InfoTranslate = ref([]) as any;
const typeShow = ref(null);
const ShowTranslate = ref(false);
const ShowAbstract = ref(false);
const AbstractInfo = ref('') as any;
const ShowExtract = ref(false);
const ExtractInfo = ref('') as any;

const showAiQA = ref(false);

/************************************************ AI问答 start*/
const isFocused = ref(false);
const maxnum = ref(2500);
const row = ref(1);
const values = ref('') as any;
const placeholder = ref('请输入内容') as any;
const messageInput = ref('') as any;
const messages = ref([]);
const chatMessages = ref(null);
const textInputRefs = ref();

const isSpeakType = ref(1); //1:静默状态,还未点击开始录音,2:开始录音,3:结束录音,正在转换中

// 定义Recorder对象
const recorder: any = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1 // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
});
// 拿到输入框的值
const inputChangeMethod = (e) => {
  values.value = e;
  messageInput.value = e;
};

// 更新 rows 值
const updateRows = (newRow: number) => {
  row.value = newRow;
};

// 聚焦时的操作
const focusMethod = () => {
  row.value = 4;
  nextTick(() => {
    scrollToBottom();
  });
  // if (this.CancelBtn == false) {
  //   this.showBtn = true;
  // }
  // if (this.showBtn == true) {
  //   this.CancelBtn == true;
  // }

  // this.CancelBtn = true;
};

// 发送消息
const sendMessage = () => {
  if (messageInput.value.trim() === '') {
    // 如果消息为空且文件列表为空，则弹出警告
    proxy?.$modal.msgWarning(proxy.$t('chatGpt.chatMsg1'));
    return;
  } else {
    let formdata = new FormData();
    // formdata.append('file', files.value);
    formdata.append('content', messageInput.value);
  }

  if (messageInput.value.trim()) {
    messages.value.push({
      content: messageInput.value,
      isUser: true
    });
    messageInput.value = '';
    values.value = '';
    row.value = 1;

    // 模拟其他用户的回复
    setTimeout(() => {
      messages.value.push({
        content: '这是一个自动回复消息。',
        isUser: false
      });
      nextTick(() => {
        scrollToBottom();
      });
    }, 1000);

    // 滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }
};

/*****************************************录音start */
// 聚焦事件
const handleFocus = () => {
  isFocused.value = true;

  nextTick(() => {
    scrollToBottom();
  });
};
// 失焦事件
const handleBlur = () => {
  isFocused.value = false;
};
// 开始录音
const startRecordAudio = () => {
  //@ts-ignore
  Recorder?.getPermission().then(
    () => {
      // console.log("开始录音");
      recorder.start(); // 开始录音
      messageInput.value = '';
      isSpeakType.value = 2;
    },
    (error: any) => {
      proxy.$modal.msgWarning('请先允许该网页使用麦克风');
      // console.log(`${error.name} : ${error.message}`);
    }
  );
};

// 停止录音
const stopRecordAudio = () => {
  recorder.stop();
  var wavBlob = recorder.getWAVBlob();
  isSpeakType.value = 3;
  var formData = new FormData();
  const newbolb = new Blob([wavBlob], { type: 'audio/wav' });
  // //获取当时时间戳作为文件名
  const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav');
  formData.append('file', fileOfBlob);
  axios
    .post('/stt', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((res) => {
      console.log(res);
      messageInput.value = res.data;
      isSpeakType.value = 1;
      textInputRefs.value.focus();
    })
    .catch((err) => {
      isSpeakType.value = 1;
      proxy.$modal.msgError('语音识别失败，请重试');
    });
};
/*****************************************录音end */

/**input事件-------------------------start */
// 键盘按下事件--阻止回车换行,执行ctrl + enter换行
const handleKeyPress = (event: any) => {
  // console.log('🚀 ~ handleKeyPress ~ event:', event);
  if (event.keyCode == 13) {
    if (!event.ctrlKey) {
      event.preventDefault();
    } else {
      messageInput.value += '\n';
    }
  }
};

// 回车提交事件
const enterSubmit = (e) => {
  e.preventDefault();
  sendMessage();
};

/**input事件-------------------------end */

/************************************************ AI问答 end*/

watch(
  typeShow,
  (newValue, oldValue) => {
    // console.log(`isTableTopMoreText 发生变化: 从 ${oldValue} 变为 ${newValue}`);
  },
  { deep: true, immediate: true }
);

// 外部调用打开弹框
const openFileDialog = (val, type) => {
  console.log('🚀 ~ openFileDialog ~ val:', val);
  typeShow.value = type; // 设置当前文件类型
  InfoData.value = { ...val[0] }; // 复制文件数据到 InfoData

  // 初始化所有状态为 false，避免遗漏
  ShowAbstract.value = false;
  ShowExtract.value = false;
  showAiQA.value = false;
  drawer.value = false;
  ShowTranslate.value = false;

  // 辅助函数，用于设置页面显示的状态
  const setShowFlags = (abstract, extract, aiQA, translate, drawerFlag) => {
    ShowAbstract.value = abstract;
    ShowExtract.value = extract;
    showAiQA.value = aiQA;
    ShowTranslate.value = translate;
    drawer.value = drawerFlag;
  };

  // 根据不同类型，设置对应的显示状态并执行相应的操作
  switch (type) {
    case 1: // AI总结
      setShowFlags(false, false, false, false, true); // 显示总结界面
      if (InfoData.value.id) getAiSummary(); // 如果有ID，获取AI总结
      break;
    case 2: // AI翻译
      setShowFlags(false, false, false, true, false); // 显示翻译界面
      if (InfoData.value.id) getAiTranslate(); // 如果有ID，进行AI翻译
      break;
    case 3: // AI摘要
      setShowFlags(true, false, false, false, false); // 显示摘要界面
      if (InfoData.value.id) getAiAbstract(); // 如果有ID，获取AI摘要
      break;
    case 4: // AI抽取
      setShowFlags(false, true, false, false, false); // 显示抽取界面
      if (InfoData.value.id) getAiExtract(); // 如果有ID，获取AI抽取
      break;
    case 5: // AI问答
      setShowFlags(false, false, true, false, false); // 显示问答界面
      messageInput.value = ''; // 重置消息输入框
      values.value = ''; // 重置值
      row.value = 1; // 重置行数
      messages.value = []; // 清空消息列表
      break;
    default:
      console.warn('Unknown type:', type); // 默认情况下警告未知类型
  }
};

const openFileDialog00 = (val, type) => {
  console.log('🚀 ~ openFileDialog ~ val:', val);
  typeShow.value = type;
  InfoData.value = { ...val[0] };
  // 总结
  if (type == 1) {
    ShowAbstract.value = false;
    ShowExtract.value = false;
    showAiQA.value = false;
    drawer.value = true;
    ShowTranslate.value = false;
    if (InfoData.value.id) {
      getAiSummary();
    }
  } else if (type == 2) {
    //AI翻译
    ShowTranslate.value = true;
    ShowAbstract.value = false;
    ShowExtract.value = false;
    showAiQA.value = false;
    drawer.value = false;
    if (InfoData.value.id) {
      getAiTranslate();
    }
  } else if (type == 3) {
    //AI摘要
    ShowTranslate.value = false;
    ShowExtract.value = false;
    showAiQA.value = false;
    drawer.value = false;
    ShowAbstract.value = true;
    if (InfoData.value.id) {
      getAiAbstract();
    }
  } else if (type == 4) {
    //AI抽取
    ShowTranslate.value = false;
    showAiQA.value = false;
    drawer.value = false;
    ShowAbstract.value = false;
    ShowExtract.value = true;
    if (InfoData.value.id) {
      getAiExtract();
    }
  } else if (type == 5) {
    // AI问答
    ShowTranslate.value = false;
    drawer.value = false;
    ShowAbstract.value = false;
    ShowExtract.value = false;
    showAiQA.value = true;
    messageInput.value = '';
    values.value = '';
    row.value = 1;
    messages.value = [];
    // if (InfoData.value.id) {
    // }
  }
};

// 总结信息
const getAiSummary00 = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';

  try {
    // 获取AI总结的响应
    const res = (await ApiAISummary(oParam)) as any;

    // 过滤并拼接非 "data:" 字段的内容
    const filteredResult = res
      .split('data:') // 按 'data:' 分割字符串
      .filter((item) => item.trim() !== '') // 过滤空字符串
      .map((item) => item.trim()) // 移除两边的空格
      .join(' '); // 将过滤后的部分重新拼接成一个字符串

    // 将处理后的内容赋值给 txtInfo
    txtInfo.value = filteredResult;

    // 停止加载
    loading.value = false;
  } catch (error) {
    // 发生错误时停止加载
    loading.value = false;
  }
};

const getAiSummary = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';
  ExtractInfo.value = '';

  await fetch(`${import.meta.env.VITE_APP_BASE_API}/aiqa/personal/chat/document/summary`, {
    method: 'POST',
    timeout: 0,
    headers: {
      Authorization: 'Bearer ' + getToken(),
      'Content-Type': 'application/json',
      clientid: import.meta.env.VITE_APP_CLIENT_ID
    },
    body: JSON.stringify(oParam)
  } as any)
    .then((response: any) => {
      return response;
    })
    .then(async (response: any) => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let charIndex = 0;
      let messageContent = '';

      // 使用 setInterval 来模拟逐字显示效果
      const typeEffect = () => {
        if (charIndex < messageContent.length) {
          // 每次读取一部分数据后，将其逐字追加到 txtInfo
          txtInfo.value += messageContent.charAt(charIndex);

          charIndex++;
        } else {
          clearInterval(typeInterval); // 如果已完成显示，停止
        }
      };

      const typeInterval = setInterval(typeEffect, 50); // 每 50ms 显示一个字符

      while (1) {
        // 循环读取内容
        const { done, value } = await reader.read();
        if (done) {
          loading.value = false;
          return;
        }

        // 将读取到的内容解码为字符串
        const text = decoder.decode(value, { stream: true });

        // 按 "data:" 分割并清理空字符串
        const filteredResult = text
          .split('data:') // 按 'data:' 分割字符串
          .filter((item) => item.trim() !== '') // 过滤空字符串
          .map((item) => item.trim()) // 移除两边的空格
          .join(' '); // 将过滤后的部分重新拼接成一个字符串

        let Datafiltered = filteredResult
          .replace(/\s+/g, '') // 去除所有空格
          .trim(); // 去除前后空格
        // 将拼接后的文本内容赋值给 messageContent，用于流式更新 txtInfo
        messageContent += Datafiltered;

        // 继续执行逐字显示
        if (charIndex < messageContent.length) {
          // 如果还有新内容，继续触发逐字显示
          typeInterval;
        }
      }
    })
    .catch((error) => {
      // txtInfo.value='总结内容出错,请重试!'
      loading.value = false;
    });
};

//翻译信息
const getAiTranslate00 = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';

  try {
    // 获取AI总结的响应
    const res = (await ApiAITranslate(oParam)) as any;
    // 过滤并拼接非 "data:" 字段的内容
    const filteredResult = res
      .split('data:') // 按 'data:' 分割字符串
      .filter((item) => item.trim() !== '') // 过滤空字符串
      .map((item) => item.trim()) // 移除两边的空格
      .join(' '); // 将过滤后的部分重新拼接成一个字符串

    TranslateInfo.value = filteredResult;
    // 停止加载
    loading.value = false;
  } catch (error) {
    // 发生错误时停止加载
    loading.value = false;
  }
};

const getAiTranslate = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';
  ExtractInfo.value = '';

  await fetch(`${import.meta.env.VITE_APP_BASE_API}/aiqa/personal/chat/documentary/translation`, {
    method: 'POST',
    timeout: 0,
    headers: {
      Authorization: 'Bearer ' + getToken(),
      'Content-Type': 'application/json',
      clientid: import.meta.env.VITE_APP_CLIENT_ID
    },
    body: JSON.stringify(oParam)
  } as any)
    .then((response: any) => {
      return response;
    })
    .then(async (response: any) => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let charIndex = 0;
      let messageContent = '';

      // 使用 setInterval 来模拟逐字显示效果
      const typeEffect = () => {
        if (charIndex < messageContent.length) {
          // 每次读取一部分数据后，将其逐字追加到 TranslateInfo
          TranslateInfo.value += messageContent.charAt(charIndex);
          charIndex++;
        } else {
          clearInterval(typeInterval); // 如果已完成显示，停止
        }
      };

      const typeInterval = setInterval(typeEffect, 50); // 每 50ms 显示一个字符

      while (1) {
        // 循环读取内容
        const { done, value } = await reader.read();
        if (done) {
          loading.value = false;
          return;
        }

        // 将读取到的内容解码为字符串
        const text = decoder.decode(value, { stream: true });

        // 按 "data:" 分割并清理空字符串
        const filteredResult = text
          .split('data:') // 按 'data:' 分割字符串
          .filter((item) => item.trim() !== '') // 过滤空字符串
          .map((item) => item.trim()) // 移除两边的空格
          .join(' '); // 将过滤后的部分重新拼接成一个字符串
        // let Datafiltered = filteredResult
        //   .replace(/\s+/g, '') // 去除所有空格
        //   .trim(); // 去除前后空格
        // 将拼接后的文本内容赋值给 messageContent，用于流式更新 TranslateInfo
        messageContent += filteredResult;

        // 继续执行逐字显示
        if (charIndex < messageContent.length) {
          // 如果还有新内容，继续触发逐字显示
          typeInterval;
        }
      }
    })
    .catch((error) => {
      console.error('Error:', error);
      loading.value = false;
    });
};

//摘要
const getAiAbstract00 = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';

  try {
    // 获取AI总结的响应
    const res = (await ApiAIAbstract(oParam)) as any;

    // 过滤并拼接非 "data:" 字段的内容
    const filteredResult = res
      .split('data:') // 按 'data:' 分割字符串
      .filter((item) => item.trim() !== '') // 过滤空字符串
      .map((item) => item.trim()) // 移除两边的空格
      .join(' '); // 将过滤后的部分重新拼接成一个字符串

    AbstractInfo.value = filteredResult;
    // 停止加载
    loading.value = false;
  } catch (error) {
    // 发生错误时停止加载
    loading.value = false;
  }
};

const getAiAbstract = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';
  ExtractInfo.value = '';

  await fetch(`${import.meta.env.VITE_APP_BASE_API}/aiqa/personal/chat/documentary/abstract`, {
    method: 'POST',
    timeout: 0,
    headers: {
      Authorization: 'Bearer ' + getToken(),
      'Content-Type': 'application/json',
      clientid: import.meta.env.VITE_APP_CLIENT_ID
    },
    body: JSON.stringify(oParam)
  } as any)
    .then((response: any) => {
      return response;
    })
    .then(async (response: any) => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let charIndex = 0;
      let messageContent = '';

      // 使用 setInterval 来模拟逐字显示效果
      const typeEffect = () => {
        if (charIndex < messageContent.length) {
          // 每次读取一部分数据后，将其逐字追加到 AbstractInfo
          AbstractInfo.value += messageContent.charAt(charIndex);
          charIndex++;
        } else {
          clearInterval(typeInterval); // 如果已完成显示，停止
        }
      };

      const typeInterval = setInterval(typeEffect, 50); // 每 50ms 显示一个字符

      while (1) {
        // 循环读取内容
        const { done, value } = await reader.read();
        if (done) {
          loading.value = false;
          return;
        }

        // 将读取到的内容解码为字符串
        const text = decoder.decode(value, { stream: true });

        // 按 "data:" 分割并清理空字符串
        const filteredResult = text
          .split('data:') // 按 'data:' 分割字符串
          .filter((item) => item.trim() !== '') // 过滤空字符串
          .map((item) => item.trim()) // 移除两边的空格
          .join(' '); // 将过滤后的部分重新拼接成一个字符串

        let Datafiltered = filteredResult
          .replace(/\s+/g, '') // 去除所有空格
          .trim(); // 去除前后空格
        // 将拼接后的文本内容赋值给 messageContent，用于流式更新 TranslateInfo
        messageContent += Datafiltered;

        // 继续执行逐字显示
        if (charIndex < messageContent.length) {
          // 如果还有新内容，继续触发逐字显示
          typeInterval;
        }
      }
    })
    .catch((error) => {
      console.error('Error:', error);
      loading.value = false;
    });
};

//抽取
const getAiExtract00 = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';
  ExtractInfo.value = '';

  try {
    // 获取AI总结的响应
    const res = (await ApiAIExtract(oParam)) as any;

    // 过滤并拼接非 "data:" 字段的内容
    const filteredResult = res
      .split('data:') // 按 'data:' 分割字符串
      .filter((item) => item.trim() !== '') // 过滤空字符串
      .map((item) => item.trim()) // 移除两边的空格
      .join(' '); // 将过滤后的部分重新拼接成一个字符串

    ExtractInfo.value = filteredResult;
    // 停止加载
    loading.value = false;
  } catch (error) {
    // 发生错误时停止加载
    loading.value = false;
  }
};

const getAiExtract = async () => {
  let oParam = {
    fileType: InfoData.value.suffix,
    storageId: InfoData.value.storageId
  };

  loading.value = true;
  txtInfo.value = '';
  TranslateInfo.value = '';
  AbstractInfo.value = '';
  ExtractInfo.value = '';

  await fetch(`${import.meta.env.VITE_APP_BASE_API}/aiqa/personal/chat/documentary/extract`, {
    method: 'POST',
    timeout: 0,
    headers: {
      Authorization: 'Bearer ' + getToken(),
      'Content-Type': 'application/json',
      clientid: import.meta.env.VITE_APP_CLIENT_ID
    },
    body: JSON.stringify(oParam)
  } as any)
    .then((response: any) => {
      return response;
    })
    .then(async (response: any) => {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let charIndex = 0;
      let messageContent = '';

      // 使用 setInterval 来模拟逐字显示效果
      const typeEffect = () => {
        if (charIndex < messageContent.length) {
          // 每次读取一部分数据后，将其逐字追加到 ExtractInfo
          ExtractInfo.value += messageContent.charAt(charIndex);
          charIndex++;
        } else {
          clearInterval(typeInterval); // 如果已完成显示，停止
        }
      };

      const typeInterval = setInterval(typeEffect, 50); // 每 50ms 显示一个字符

      while (1) {
        // 循环读取内容
        const { done, value } = await reader.read();
        if (done) {
          loading.value = false;
          return;
        }

        // 将读取到的内容解码为字符串
        const text = decoder.decode(value, { stream: true });

        // 按 "data:" 分割并清理空字符串
        const filteredResult = text
          .split('data:') // 按 'data:' 分割字符串
          .filter((item) => item.trim() !== '') // 过滤空字符串
          .map((item) => item.trim()) // 移除两边的空格
          .join(' '); // 将过滤后的部分重新拼接成一个字符串

        let Datafiltered = filteredResult
          .replace(/\s+/g, '') // 去除所有空格
          .trim(); // 去除前后空格
        // 将拼接后的文本内容赋值给 messageContent，用于流式更新 TranslateInfo
        messageContent += Datafiltered;

        // 继续执行逐字显示
        if (charIndex < messageContent.length) {
          // 如果还有新内容，继续触发逐字显示
          typeInterval;
        }
      }
    })
    .catch((error) => {
      console.error('Error:', error);
      loading.value = false;
    });
};

// 流式数据会有被截断的情况，需要做一些容错处理
const chunkRef = ref();
const handleChunkData = (chunk: string) => {
  chunk = chunk.trim();
  // 如果存在上一个切片
  if (chunkRef.value) {
    chunk = chunkRef.value + chunk;
    chunkRef.value = '';
  }

  // 如果存在done,认为是完整切片且是最后一个切片
  if (chunk.includes('[DONE]')) {
    return chunk;
  }

  // 最后一个字符串不为}，则默认切片不完整，保存与下次拼接使用（这种方法不严谨，但已经能解决大部分场景的问题）
  if (chunk[chunk.length - 1] !== '}') {
    chunkRef.value = chunk;
  }
  return chunk;
};

// 滚动到底部
const scrollToBottom = () => {
  const chatMag = chatMessages.value;
  chatMag.scrollTop = chatMag.scrollHeight;
};

/**icon转换 */
const selectSvgIcons = (v: any) => {
  return proxy.$yuUtils.selectSvgIcon(v);
};

onMounted(() => {});

defineExpose({
  //调用组件需要导出 v-model的变量
  openFileDialog
});
</script>

<style lang="scss" scoped>
/* 聊天消息样式 */
.ai-message .message-content-wrapper {
  display: flex;
  align-items: center;
}

.ai-message .AIavatar {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

/* 用户消息样式 */
.user-message .message-content {
  background-color: #f1f1f1;
  color: #333;
}

.ai-message .message-content {
  background-color: #e0f7fa;
  color: #00796b;
}

/* loading 状态的样式 */
.ai-message .message-content-wrapper .message-content {
  color: #999;
  font-style: italic;
}

.loading-text {
  color: #888;
  font-style: italic;
  animation: loading 1s infinite;
}

@keyframes loading {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}
// 输入框的样式
.input-bot {
  // position: relative;

  width: 100%;
  height: 100%;

  .page_input {
    width: 100%;
    // max-width: 760px;
    // max-height: 150px;
    overflow-y: auto;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: flex-end;

    .create_btn {
      margin-left: 8px;
      // margin-bottom: 8px;
    }

    .img2 {
      width: 16px;
      height: 16px;
    }

    .input_box {
      flex: 1;
      display: flex;
      align-items: flex-end;
      background-color: #ffffff;
      border-radius: 6px;
      // border: 1px solid #ffdeae;
      box-shadow: 0px 0px 8px 0px rgba(240, 143, 0, 0.06);
      overflow-y: auto;
      padding: 8px;
      margin: 0 auto;

      :deep(.el-textarea__inner) {
        box-shadow: none;
      }

      .btn_box {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
      }
    }

    .voice_box {
      height: 20px;
      cursor: pointer;

      .SpeakType3 {
        width: 60px;
        font-size: 12px;
        color: #b3b0c3;
      }
    }

    .loaderRectangle {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 0 3px;
    }

    .loaderRectangle div {
      width: 4px;
      height: 8px;
      animation: 0.9s ease-in-out infinite;
      background: #3662ec;
      box-shadow: 0 0 20px rgba(18, 31, 53, 0.3);
    }

    .loaderRectangle div:nth-child(1) {
      animation-name: rectangleOneAnim;
      animation-delay: 1s;
    }

    @keyframes rectangleOneAnim {
      0% {
        height: 8px;
      }

      40% {
        height: 15px;
      }

      100% {
        height: 8px;
      }
    }

    .loaderRectangle div:nth-child(2) {
      animation-name: rectangleTwoAnim;
      animation-delay: 1.1s;
    }

    @keyframes rectangleTwoAnim {
      0% {
        height: 8px;
      }

      40% {
        height: 20px;
      }

      100% {
        height: 8px;
      }
    }

    .loaderRectangle div:nth-child(3) {
      animation-name: rectangleThreeAnim;
      animation-delay: 1.2s;
    }

    @keyframes rectangleThreeAnim {
      0% {
        height: 8px;
      }

      40% {
        height: 25px;
      }

      100% {
        height: 8px;
      }
    }

    .loaderRectangle div:nth-child(4) {
      animation-name: rectangleFourAnim;
      animation-delay: 1.3s;
    }

    @keyframes rectangleFourAnim {
      0% {
        height: 8px;
      }

      40% {
        height: 20px;
      }

      100% {
        height: 8px;
      }
    }

    .loaderRectangle div:nth-child(5) {
      animation-name: rectangleFiveAnim;
      animation-delay: 1.4s;
    }

    @keyframes rectangleFiveAnim {
      0% {
        height: 8px;
      }

      40% {
        height: 15px;
      }

      100% {
        height: 8px;
      }
    }

    .sendBtn {
      width: 28px;
      height: 28px;
      text-align: center;
      line-height: 28px;
      background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
      // background-color: #f08f00;
      color: #ffffff;
      border-radius: 6px;
      // margin-left: 8px;
      font-size: 17px;
      cursor: pointer;
    }
  }
}

/**************************AI问答 start */
/* 头像样式 */
.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  background-color: #56abfb;
  margin-right: 8px;
  /* 为了给消息内容腾出空间 */
}

.AIavatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  /* 为了给消息内容腾出空间 */
  border: 1px solid #56abfb;
  // background-color: #56abfb;
}

.avatarUser {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  background-color: #56abfb;
  margin-left: 8px;
  /* 为了给消息内容腾出空间 */
}

/* 聊天容器 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(94vh - 75px);
  /* 占用视口高度，减去头部/底部的空间 */
  background-color: #fff;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  /* 超过内容时滚动 */
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
  display: flex;
  flex-direction: column;
}

/* 每条消息 */
.message-content-wrapper {
  display: flex;
  // align-items: flex-start;
  align-items: center;
  margin-bottom: 10px;
  //max-width: 75%; /* 限制最大宽度 */
  // padding: 5px;
}

.messageisUser {
  display: flex;
  // align-items: flex-start;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 10px;
  //max-width: 75%; /* 限制最大宽度 */
  // padding: 5px;
}

/* 用户消息的样式（右对齐） */
.user-message {
  flex-direction: row-reverse;
  /* 用户消息右对齐 */
  justify-content: flex-end;
}

/* AI（或其他人的）消息样式（左对齐） */
.ai-message {
  flex-direction: row;
  /* AI消息左对齐 */
  justify-content: flex-start;
}

/* 消息内容样式 */
.message-content {
  padding: 10px;
  border-radius: 10px;
  word-wrap: break-word;
  line-height: 1.4;
  max-width: 90%;
  /* 消息内容最大宽度 */
}

/* 用户的消息样式 */
.message-content.user {
  background-color: #0084ff;
  color: white;
  align-self: flex-end;
  /* 用户消息靠右对齐 */
}

/* 其他用户或AI的消息样式 */
.message-content.other {
  background-color: #e1e1e1;
  color: black;
  align-self: flex-start;
  /* AI消息靠左对齐 */
}

/* 输入框容器 */
.chat-input-container {
  display: flex;
  align-items: center;
  padding: 3px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  // background-image: linear-gradient(to right, #6ee0dd 0%, #2964f0 100%);
  transition:
    background-color 0.8s ease,
    box-shadow 0.8s ease;
  /* 添加过渡效果 */
}

// .icon_search {
//   position: absolute;
//   top: -3px;
//   left: 5px;
// }

.focused {
  background-image: linear-gradient(to right, rgba(110, 224, 221, 0) 0%, rgba(41, 100, 240, 0) 100%);
  background-color: rgba(110, 224, 221, 1);
  /* 默认颜色 */
  box-shadow: 0 0 15px rgba(41, 100, 240, 0.3);
  /* 可以增加聚焦时的阴影效果 */
}

.focused {
  animation: gradientEffect 0.8s ease forwards;
  /* 使用动画 */
}

@keyframes gradientEffect {
  0% {
    background-image: linear-gradient(to right, #6ee0dd 0%, #6ee0dd 100%);
  }

  100% {
    background-image: linear-gradient(to right, #6ee0dd 0%, #2964f0 100%);
  }
}

/* 输入框样式 */
.chat-input {
  flex: 1;
  padding: 10px;
  border-radius: 20px;
  // border: 1px solid #ddd;
  // margin-right: 10px;
}

/* 发送按钮样式 */
.send-button {
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 20px;
}

/**************************AI问答 end */

.header-top {
  display: flex;
  align-items: center;

  .top {
    letter-spacing: 1.45px;
    font-weight: 600;
    font-size: 1.125rem;
  }
}
:deep(.el-drawer__header) {
  margin-bottom: 0;
}

.content {
  p {
    margin: 0;
  }

  .title {
    letter-spacing: 1.85px;
    font-weight: 600;
    color: #5d5d5d;
    font-size: 1.125rem;
    line-height: 1.75rem;
    margin-bottom: 12px;
  }

  .info {
    // border: 1px solid red;
    height: calc(100vh - 160px);
    overflow-y: auto;

    .text {
      letter-spacing: 1.85px;
      font-size: 1.125rem;
      line-height: 1.85rem;
      border-radius: 1.5rem;
      background-color: #e8e8e880;
      padding-left: 1.25rem;
      padding-right: 1.25rem;
      padding-bottom: 0.625rem;
      padding-top: 0.625rem;
    }
  }
}
</style>
